package com.letoken.platform.repo.sss.servie.impl;



import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.letoken.platform.pub.exception.ApiServiceException;
import com.letoken.platform.pub.token.TokenUtil;
import com.letoken.platform.pub.util.MD5Util;
import com.letoken.platform.pub.util.SignUtil;
import com.letoken.platform.repo.app.redis.AppLoginTokenRedis;
import com.letoken.platform.repo.app.redis.AppUserTokenRedis;
import com.letoken.platform.repo.sss.dao.AdminTokenConfigMapper;
import com.letoken.platform.repo.sss.dao.AppUserInfoMapper;
import com.letoken.platform.repo.sss.po.AdminTokenConfig;
import com.letoken.platform.repo.sss.po.AppUserInfo;
import com.letoken.platform.repo.sss.po.AppUserWallet;
import com.letoken.platform.repo.sss.req.ForgetPasswordReq;
import com.letoken.platform.repo.sss.req.LoginReq;
import com.letoken.platform.repo.sss.req.RegisterReq;
import com.letoken.platform.repo.sss.servie.AppUserInfoService;
import com.letoken.platform.repo.sss.servie.AppUserWalletSSSService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 作者
 * @since 2024-09-05
 */
@Service
public class AppUserInfoServiceImpl extends ServiceImpl<AppUserInfoMapper, AppUserInfo> implements AppUserInfoService {

    @Resource
    AdminTokenConfigMapper adminTokenConfigMapper;

    @Resource
    AppUserInfoMapper appUserInfoMapper;

    @Autowired
    AppUserWalletSSSService appUserWalletService;

    private static String passwordKey = "shabiwanyi";
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void register(RegisterReq req) {
       List<AdminTokenConfig> adminTokenConfigs =  adminTokenConfigMapper.selectList(new QueryWrapper<AdminTokenConfig>().orderByAsc("id"));

       AppUserInfo appUserInfo =  appUserInfoMapper.selectOne(new QueryWrapper<AppUserInfo>().eq("name",req.getUser()));
       if( appUserInfo != null) throw new ApiServiceException("賬戶名已存在");

        AppUserInfo userInfo =  appUserInfoMapper.selectOne(new QueryWrapper<AppUserInfo>().eq("name",req.getInvitationCode()));
        if( userInfo == null) throw new ApiServiceException("該推薦人不存在");

        LocalDateTime dateTime = LocalDateTime.now();
        AppUserInfo newAppUserInfo = new AppUserInfo();
        newAppUserInfo.setUser(req.getUser());
        newAppUserInfo.setUser(MD5Util.MD5(passwordKey+req.getPassword()));
        newAppUserInfo.setInviteId(userInfo.getId().toString());
        newAppUserInfo.setCodeR(req.getUser()+"_r");
        newAppUserInfo.setCodeL(req.getUser()+"_l");
        newAppUserInfo.setCode(req.getUser());
        newAppUserInfo.setCreateTime(dateTime);
        newAppUserInfo.setUpdateTime(dateTime);
        appUserInfoMapper.insert(newAppUserInfo);

        List<AppUserWallet> add = new ArrayList<>();
        for (AdminTokenConfig adminToken:adminTokenConfigs) {
            AppUserWallet appUserWallet = new AppUserWallet();
            appUserWallet.setUserId(newAppUserInfo.getId());
            appUserWallet.setTokenId(adminToken.getId());
            appUserWallet.setCreateTime(dateTime);
            appUserWallet.setUpdateTime(dateTime);
            add.add(appUserWallet);
        }
        appUserWalletService.saveBatch(add);
    }

    @Override
    public String login(LoginReq req) {
        AppUserInfo appUserInfo =  appUserInfoMapper.selectOne(new QueryWrapper<AppUserInfo>().eq("name",req.getUser()).eq("password",MD5Util.MD5(passwordKey+req.getPassword())));
        if( appUserInfo == null) throw new ApiServiceException("賬戶名不存在");
        String queryToken = AppUserTokenRedis.me().getValue(appUserInfo.getId().toString());// appUser.getToken();
        if (StringUtils.isNotBlank(queryToken)) {
            AppLoginTokenRedis.me().del(queryToken);
        }
        String token =  TokenUtil.generateToken();
        AppUserTokenRedis.me().put(appUserInfo.getId().toString(), token);
        return TokenUtil.generateToken();
    }

    @Override
    public void forgetPassword(ForgetPasswordReq req) {
        if(!SignUtil.recoverSignature(req.getUser(), req.getHash(), req.getAddress())) throw new ApiServiceException("重置賬戶與當前地址不匹配");
        AppUserInfo appUserInfo =  appUserInfoMapper.selectOne(new QueryWrapper<AppUserInfo>().eq("name",req.getUser()).eq("address",req.getAddress()));
        if( appUserInfo == null) throw new ApiServiceException("賬戶不存在");
        AppUserInfo appUserInfo2 = new AppUserInfo();
        appUserInfo2.setId(appUserInfo.getId());
        appUserInfo2.setPassword(MD5Util.MD5(passwordKey+req.getPassword()));
        appUserInfo2.updateById();
    }
}
